<template>
  <div class="w-full h-full rounded-xl">
<!--    <div class=" w-full h-full" >-->
      <!-- 顶部标题和数据概览区域 -->
      <div class="main-content">
        <!-- 左侧标题 -->
        <div class="header flex">
          <div class="header-left">
            <div class="title-section">
              <div class="title-icon">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="title-content">
                <h2>{{ $t('tank.jiankong')}}</h2>
                <div class="title-tags">
                  <el-tag type="success" effect="dark" class="status-tag">{{ $t('tank.shishijiank')}}</el-tag>
                  <el-tag type="info" effect="plain" class="update-tag">{{ $t('tank.gengx')}} {{ currentTime }}</el-tag>
                </div>
              </div>
            </div>
            <div class="header-info">
              <div class="info-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ currentDate }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ $t('tank.zhouqi')}}</span>
              </div>
            </div>
            <div class="flex">

              <div class="header-stats mr-4">
                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon><Operation /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{sumMap.batchNumNowWPC }}</div>
                    <div class="stat-label">WPC-{{ $t('tank.Ripici')}}</div>
<!--                    <el-progress-->
<!--                      :percentage="(activeTanks / totalTanks) * 100"-->
<!--                      :stroke-width="4"-->
<!--                      :show-text="false"-->
<!--                      class="stat-progress"-->
<!--                    />-->
                  </div>
                </div>
                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon><ScaleToOriginal /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{sumMap.batchNumNowLVT}}</div>
                    <div class="stat-label">LVT-{{ $t('tank.Ripici')}}</div>
                    <!--                <div class="stat-trend">-->
                    <!--                  <span class="trend-label">较昨日</span>-->
                    <!--                  <span class="trend-value" :class="{ 'up': totalWeight > yesterdayWeight, 'down': totalWeight < yesterdayWeight }">-->
                    <!--                  {{ Math.abs(((totalWeight - yesterdayWeight) / yesterdayWeight * 100).toFixed(1)) }}%-->
                    <!--                  <el-icon v-if="totalWeight > yesterdayWeight"><ArrowUp /></el-icon>-->
                    <!--                  <el-icon v-else><ArrowDown /></el-icon>-->
                    <!--                </span>-->
                    <!--                </div>-->
                  </div>
                </div>
              </div>
                <div class="header-stats">
                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon><TrendCharts /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{sumMap.batchNumMonthWPC}}</div>
                    <div class="stat-label">WPC-{{ $t('tank.Yuepici')}}</div>
                    <!--                <div class="stat-trend">-->
                    <!--                  <span class="trend-label">较昨日</span>-->
                    <!--                  <span class="trend-value" :class="{ 'up': todayIn > yesterdayIn, 'down': todayIn < yesterdayIn }">-->
                    <!--                  {{ Math.abs(((todayIn - yesterdayIn) / yesterdayIn * 100).toFixed(1)) }}%-->
                    <!--                  <el-icon v-if="todayIn > yesterdayIn"><ArrowUp /></el-icon>-->
                    <!--                  <el-icon v-else><ArrowDown /></el-icon>-->
                    <!--                </span>-->
                    <!--                </div>-->
                  </div>
                </div>
                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon><TrendCharts /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{sumMap.batchNumMonthLVT}}</div>
                    <div class="stat-label">LVT-{{ $t('tank.Yuepici')}}</div>
                    <!--                <div class="stat-trend">-->
                    <!--                  <span class="trend-label">较昨日</span>-->
                    <!--                  <span class="trend-value" :class="{ 'up': todayOut > yesterdayOut, 'down': todayOut < yesterdayOut }">-->
                    <!--                  {{ Math.abs(((todayOut - yesterdayOut) / yesterdayOut * 100).toFixed(1)) }}%-->
                    <!--                  <el-icon v-if="todayOut > yesterdayOut"><ArrowUp /></el-icon>-->
                    <!--                  <el-icon v-else><ArrowDown /></el-icon>-->
                    <!--                </span>-->
                    <!--                </div>-->
                  </div>
                </div>
              </div>
            </div>

          </div>

        </div>

        <!-- 右侧图表 -->
        <div class="overview-section">
          <el-card class="chart-card h-full" shadow="hover">
            <template #header>
              <div class="card-header">
                <div class="header-title">
                  <el-icon><TrendCharts /></el-icon>
                  <span>{{ $t('tank.zhuangt')}}</span>
                </div>

                <div class="header-title">
                  <div class="countdown-container mr-4">
                    <span class="countdown-time">{{ countdownDisplay }}</span>
                    <span class="countdown-label">{{ $t('tank.shuxing')}}</span>
                  </div>
                  <el-button type="primary" @click="handleRefresh" icon="refresh">{{ $t('tank.shuaX')}}</el-button>
                </div>
              </div>
            </template>
            <div class="w-full h-full chart-container ">
              <div class="w-full flex mb-2" style="height: 48%">
                <cardItem v-for="item in cardList.slice(0, 6)" :key="item.title" :item="item"/>
              </div>
              <div class="w-full flex mb-2" style="height: 48%">
                <cardItem v-for="item in cardList.slice(-6)" :key="item.title" :item="item"/>
              </div>
            </div>
          </el-card>
        </div>
      </div>
<!--    </div>-->
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { getTankNum, getTankOutNum } from '@/api/tankBodyApi'
import { use } from 'echarts/core'
import * as echarts from "echarts";
import cardItem from './cardItem.vue'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  MarkLineComponent
} from 'echarts/components'
import moment from 'moment/moment'

use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  MarkLineComponent
])

const cardList = ref([])
const chartRef = ref(null)
const chartType = ref('bar')
const currentTime =ref()
const currentDate = ref()
const warningWeight = ref()
const activeTanks = ref()
const totalTanks = ref()
const totalWeight = ref(225)
const yesterdayWeight = ref(14545)
const todayIn = ref(22512)
const yesterdayIn = ref(145450)
const todayOut = ref(22512)
const yesterdayOut = ref(140)
const sumMap = ref({
  batchNumMonthLVT:0,
  batchNumMonthWPC:0,
  batchNumNowLVT:0,
  batchNumNowWPC:0,
  }
)
// const yesterdayIn = ref(145450)
// const todayOut = ref(22512)
// const yesterdayOut = ref(140)

watch(chartType, (newValue) => {
  updateChart()
})

//获取当天时间YY-MM-DD HH:mm:ss
const getCurrentTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${hours}:${minutes}:${seconds}`
  currentDate.value = `${year}-${month}-${day}`

}
const getEndList = async () => {
  try {
    const params = {
      startTime:  '',
      endTime: '',
    }
    const res = await getTankOutNum(params)
    activeTanks.value = res.data.filter(item => item.isUse).length
    totalWeight.value = parseFloat(res.data.reduce((acc, cur) => {
      const beginQty = parseFloat(cur.beginQty);
      return acc + (isNaN(beginQty) ? 0 : beginQty);
    }, 0)).toFixed(2);
    todayIn.value = parseFloat(res.data.reduce((acc, cur) => {
      const beginQty = parseFloat(cur.inQty);
      return acc + (isNaN(beginQty) ? 0 : beginQty);
    }, 0)).toFixed(2);
    todayOut.value = parseFloat(res.data.reduce((acc, cur) => {
      const beginQty = parseFloat(cur.outQty);
      return acc + (isNaN(beginQty) ? 0 : beginQty);
    }, 0)).toFixed(2);
  } catch (e) {
    console.log(e)
  }
}

const getData = async () => {
  // let list = ['Box', 'DataAnalysis', 'BellFilled',
  //   'Cpu', 'MessageBox', 'Monitor',
  //   'Document', 'ScaleToOriginal', 'Histogram',
  //   'SetUp', 'Tickets', 'DataLine']
  let list = ['Box', 'Box', 'DataAnalysis',
    'DataAnalysis', 'Cpu', 'Cpu',
    'MessageBox', 'MessageBox', 'Monitor',
    'Monitor', 'SetUp', 'SetUp']
  try {
    const res = await getTankNum()
    totalTanks.value =res.data.data.length
    console.log('数据加载成功:', res) // 添加日志
    cardList.value = res.data.data.map((item, index) => {
      return {
        ...item,
        title: item.text,
        name: item.text,
        content: parseFloat(item.remark).toFixed(2),
        weight: parseFloat(item.remark).toFixed(2),
        unit: 'kg',
        status: item.isUse,
        icon: list[index]
      }
    })

    sumMap.value = res.data.sumMap
    // 数据加载完成后更新图表
    updateChart()
  } catch (e) {
    console.error('数据加载失败:', e)
  }
}

let dataFetchTimer = null

const countdown = ref(300) // 5分钟倒计时（秒）
const countdownDisplay = ref('05:00')
let countdownTimer = null

const formatCountdown = (seconds) => {
  const mm = String(Math.floor(seconds / 60)).padStart(2, '0')
  const ss = String(seconds % 60).padStart(2, '0')
  return `${mm}:${ss}`
}

const resetCountdown = () => {
  countdown.value = 300
  countdownDisplay.value = formatCountdown(countdown.value)
}

const startCountdown = () => {
  if (countdownTimer) clearInterval(countdownTimer)
  countdownDisplay.value = formatCountdown(countdown.value)
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
      countdownDisplay.value = formatCountdown(countdown.value)
    } else {
      handleRefresh()
    }
  }, 1000)
}

const handleRefresh = async () => {
  resetCountdown()
  await getData()
  await getEndList()
  getCurrentTime()
}

onMounted(async () => {
  getCurrentTime()
  // 确保数据加载完成后初始化图表
  await getData()
  await getEndList()
  resetCountdown()
  startCountdown()
  // 每隔10秒请求一次数据
  dataFetchTimer = setInterval(() => {
    getCurrentTime()
    getData()
    getEndList()
  }, 300000)
})

onUnmounted(() => {
  // 清除定时器，避免内存泄漏
  if (dataFetchTimer) clearInterval(dataFetchTimer)
  if (countdownTimer) clearInterval(countdownTimer)
})

const updateChart = () => {
  if (chartRef.value && cardList.value.length > 0) {
    try {
      if (chartType.value === 'bar') {
        chartRef.value.clear()
        chartRef.value.setOption(getBarOption())
      } else {
        chartRef.value.clear()
        chartRef.value.setOption(getPieOption())
      }
    } catch (error) {
      console.error('图表更新失败:', error)
    }
  } else {
    console.warn('图表数据为空或未初始化')
  }
}
</script>

<style scoped lang="scss">
//.tank-monitor {
//  min-height: 100vh;
//}

.main-content {
  display: flex;
  gap: 20px;
  //margin-bottom: 10px;
}

.header {
  flex: 0.2;
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  height: 100%;
}

.overview-section {
  flex: 0.8;
}

.header-left {
  display: flex;
  flex-direction: column;
  //gap: 15px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-icon .el-icon {
  font-size: 24px;
  color: #fff;
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title-content h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.title-tags {
  display: flex;
  gap: 8px;
  align-items: center;
}

.status-tag {
  font-size: 13px;
}

.update-tag {
  font-size: 13px;
}

.header-info {
  display: flex;
  gap: 20px;
  align-items: center;
  padding: 8px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 13px;
}

.info-item .el-icon {
  font-size: 16px;
  color: #909399;
}

.divider {
  width: 100%;
  height: 1px;
  margin: 5px 0;
  background: linear-gradient(to right,
    transparent 0%,
    rgba(220, 223, 230, 0.3) 10%,
    rgba(220, 223, 230, 0.6) 20%,
    rgba(220, 223, 230, 0.6) 80%,
    rgba(220, 223, 230, 0.3) 90%,
    transparent 100%
  );
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.05);
}

.header-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 0px;
}

.stat-card {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 7px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  border-color: #dcdfe6;
}

.stat-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.stat-icon .el-icon {
  font-size: 20px;
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.2;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 6px;
}

.trend-label {
  font-size: 12px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.trend-value.up {
  color: #67C23A;
}

.trend-value.down {
  color: #F56C6C;
}

.trend-value .el-icon {
  font-size: 12px;
}

.stat-progress {
  margin-top: 4px;
}

.header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chart-card {
  height: 295px;
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-container {
  height: 230px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 10px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.header-title .el-icon {
  width: 24px;
  height: 24px;
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 14px;
}

.data-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 100%;
}

.data-card {
  flex: 1;
  margin-bottom: 0;
  transition: all 0.3s;
}

.data-card:hover {
  transform: translateY(-5px);
}

.data-card-content {
  display: flex;
  align-items: center;
  padding: 12px;
}

.data-icon {
  font-size: 20px;
  color: #409EFF;
  margin-right: 12px;
}

.data-info {
  flex: 1;
}

.data-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.data-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 6px;
}

.data-trend {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 6px;
}

.trend-label {
  font-size: 12px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.trend-value.up {
  color: #67C23A;
}

.trend-value.down {
  color: #F56C6C;
}

.trend-value .el-icon {
  font-size: 12px;
}

.data-progress {
  margin-top: 4px;
}

.tank-table {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.date-picker {
  width: 240px;
}

:deep(.el-table) {
  --el-table-border-color: #EBEEF5;
  --el-table-header-bg-color: #F5F7FA;
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}


:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

:deep(.el-card__header) {
  padding: 15px;
  border-bottom: 1px solid #EBEEF5;
  //background-color: #F5F7FA;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.highlight-green {
  color: #67C23A;
  font-weight: bold;
}

.highlight-red {
  color: #F56C6C;
  font-weight: bold;
}

.data-icon.warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F3B760 100%);
}

.data-icon.efficiency {
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
}

.data-icon.material {
  background: linear-gradient(135deg, #909399 0%, #C0C4CC 100%);
}

.data-icon.trend {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
}

.trend-value.warning {
  color: #E6A23C;
}
.el-card__body{
  padding: 0;
}
.countdown-container {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #333;
  background: linear-gradient(90deg, #f0f0f0, #e0e0e0);
  padding: 6px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    background: linear-gradient(90deg, #e0e0e0, #d0d0d0);
  }
}

.countdown-time {
  font-weight: bold;
  font-size: 18px;
  color: #1890ff;
  margin-right: 6px;
  transition: color 0.3s ease;
}

.countdown-label {
  font-size: 14px;
  color: #666;
}

.el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
  transition: all 0.3s ease;

  &:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
    transform: translateY(-1px);
    box-shadow: 0 4px 10px rgba(24, 144, 255, 0.2);
  }

  .el-button__icon {
    transition: transform 0.3s ease;
  }

  &:hover .el-button__icon {
    transform: rotate(15deg);
  }
}
:deep(.el-card__body){
  padding: 0 5px;
}
</style>
